﻿/**
 * @author 毕伟伦
 * 2012-3-19 创建
 */
package cn.edu.zjusc.Webservice;

import java.math.BigDecimal;
import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jws.*;
import javax.jws.soap.SOAPBinding;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.jboss.wsf.spi.annotation.WebContext;

import cn.edu.zjusc.Annotation.AllInfoUpdateAccess;
import cn.edu.zjusc.POJO.ConfigInfo;
import cn.edu.zjusc.POJO.PageDataCollection;
import cn.edu.zjusc.POJO.StudentApplyInfo;
import cn.edu.zjusc.POJO.StudentBaseInfo;
import cn.edu.zjusc.POJO.StudentDetailInfo;
import cn.edu.zjusc.POJO.StudentEduBkInfo;
import cn.edu.zjusc.POJO.StudentExtendInfo;
import cn.edu.zjusc.Security.*;
import cn.edu.zjusc.Util.PersistenceHelper;

/**
 * Session Bean implementation class StudentService
 */

@Stateless
@WebService(name = "StudentService", serviceName = "StudentService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@WebContext(contextRoot = "/ZJUSCIX/Service", urlPattern = "/StudentService")
public class StudentService {

	/**
	 * 获得学生基本信息 有分页
	 * 
	 * @param index
	 *            页号 1代表第一页，索引不从0开始
	 * @return
	 */

	public PageDataCollection<StudentBaseInfo> GetAllStudentBaseInfo(
			@WebParam(name = "index") int index) {
		return getStudentInfoList("StudentBaseInfo", index);
	}

	/**
	 * 获得某个学生的基本信息
	 * 
	 * @param id
	 * @return
	 */
	public StudentBaseInfo GetStudentBaseInfoById(
			@WebParam(name = "id") BigDecimal id) {
		return (StudentBaseInfo) getStudentInfoById(id, StudentBaseInfo.class,
				"stubs_id");
	}

	/**
	 * 获得学生教育情况列表
	 * 
	 * @return
	 */
	public PageDataCollection<StudentEduBkInfo> GetAllStudentEduBkInfo() {
		return getStudentInfoList("StudentEduBkInfo", Integer.MIN_VALUE);
	}

	/**
	 * 获得某个特定学生的教育信息
	 * 
	 * @param id
	 * @return
	 */

	public StudentEduBkInfo GetStudentEduBkInfoById(
			@WebParam(name = "id") BigDecimal id) {

		return (StudentEduBkInfo) getStudentInfoById(id,
				StudentEduBkInfo.class, "stuedu_id");
	}

	/**
	 * 获得所有的学生报考信息
	 * 
	 * @return
	 */
	public PageDataCollection<StudentApplyInfo> GetAllStudentApplyInfo() {
		return getStudentInfoList("StudentApplyInfo", Integer.MIN_VALUE);
	}

	/**
	 * 获得某个学生的报考信息
	 * 
	 * @param id
	 * @return
	 */
	public StudentApplyInfo GetStudentApplyInfoById(
			@WebParam(name = "id") BigDecimal id) {

		return (StudentApplyInfo) getStudentInfoById(id,
				StudentApplyInfo.class, "stuapl_id");
	}

	/**
	 * 获得所有扩展信息
	 * 
	 * @return
	 */
	public PageDataCollection<StudentExtendInfo> GetAllStudentExtendInfo() {
		return getStudentInfoList("StudentExtendInfo", Integer.MIN_VALUE);
	}

	/**
	 * 获得某个特定学生的扩展信息
	 * 
	 * @param id
	 * @return
	 */

	public StudentExtendInfo GetStudentExtendInfoById(
			@WebParam(name = "id") BigDecimal id) {

		return (StudentExtendInfo) getStudentInfoById(id,
				StudentExtendInfo.class, "stuext_id");
	}

	/**
	 * 获得某个学生的详细信息
	 * 
	 * @param id
	 * @return 学生详细信息类
	 */
	@Interceptors(ProfileInterceptor.class)
	public StudentDetailInfo GetStudentDetailInfoById(
			@WebParam(name = "uc") UserCave uc,
			@WebParam(name = "id") BigDecimal id) {

		String hql = "select sdi from StudentDetailInfo  sdi left join  fetch  sdi.applyInfoBean left join  fetch  sdi.eduBkInfoBean left join  fetch  sdi.extendInfoBean where sdi.stubs_id=?1";
		Object[] params = { id };

		Object sdiBean = PersistenceHelper.getEntity(hql, params,
				StudentDetailInfo.class);

		return (StudentDetailInfo) sdiBean;
	}

	/**
	 * 获得某种分页的学生数据
	 * 
	 * @param queryString
	 *            类名
	 * @param index
	 *            页号 1代表第一页，索引不从0开始
	 * @return
	 */
	<T> PageDataCollection<T> getStudentInfoList(String queryString, int index) {
		return getStudentInfoList(queryString, index, null, null);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	<T> PageDataCollection<T> getStudentInfoList(String queryString, int index,
			Class<?> entityClass, String classAlias) {

		PageDataCollection<T> tDataList = new PageDataCollection<T>();

		// 1.取配置
		ConfigInfo ci = new ConfigService().readConfig();
		int pageSize = Integer.parseInt(ci.getPageSize());

		// 2.得总数
		String hqlCount = "select count(*) from " + queryString;
		Object countResult = PersistenceHelper.getEntity(hqlCount);
		int toalCount = Integer.parseInt(countResult.toString());

		// 3.拿数据
		String hql = null;
		List resultList;

		if (entityClass == null) {
			hql = "from " + queryString + " e";
			// index为Integer.MIN_VALUE就是不分页
			if (index != Integer.MIN_VALUE) {
				resultList = PersistenceHelper.executeReader(hql, null, null,
						index, pageSize);
			} else {
				resultList = PersistenceHelper.executeReader(hql);
			}

		} else {
			hql = " select " + classAlias + " from " + queryString;
			// index为Integer.MIN_VALUE就是不分页
			if (index != Integer.MIN_VALUE) {
				resultList = PersistenceHelper.executeReader(hql, null,
						entityClass, index, pageSize);
			} else {
				resultList = PersistenceHelper.executeReader(hql, null,
						entityClass);
			}
		}
		// 开始汇总分页数据
		// 设置
		tDataList.setPageSize(pageSize);
		tDataList.setDataList(resultList);
		tDataList.setTotalSize(toalCount);

		return tDataList;
	}

	/**
	 * 获得某个类型的学生信息
	 * 
	 * @param id
	 * @param studentClass
	 * @param idTextName
	 * @return
	 */
	Object getStudentInfoById(BigDecimal id, Class<?> studentClass,
			String idTextName) {

		String hql = "from " + studentClass.getSimpleName() + " e where e."
				+ idTextName + "=?1";
		Object[] params = { id };

		return PersistenceHelper.getEntity(hql, params, studentClass);

	}

	/**
	 * 删除一个学生
	 * 
	 * @param id
	 * @return
	 */
	public String DeleteStudent(@WebParam(name = "id") BigDecimal id) {

		PersistenceHelper.deleteEntity(StudentBaseInfo.class, id);

		return "删除学生成功";
	}

	/**
	 * 修改某个学生的详细信息 ! Attention !该方法暂时无效=================================
	 * 
	 * @param id
	 * @return 学生详细信息类
	 */
/*	@SuppressWarnings("unused")
	private String ModifyStudentDetailInfoById(
			@WebParam(name = "detailEntry") StudentDetailInfo sdiBean) {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("zjusc");
		EntityManager em = emf.createEntityManager();

		// 开始事务
		em.getTransaction().begin();

		em.merge(sdiBean);
		// 提交事务
		em.getTransaction().commit();

		em.close();
		emf.close();
		return "修改学生详细信息成功";
	}*/

	/**
	 * @param uc
	 * @param stubs_id
	 * @param stubs_name
	 * @param stuedu_unGrdtSchool
	 * @param stuedu_unGrdtMajor
	 * @param stubs_majorID
	 * @param stuext_learnMeanType
	 * @param index
	 * @return
	 */
	@Interceptors(ProfileInterceptor.class)
	public PageDataCollection<StudentBaseInfo> SearchStudentBaseInfo(
			@WebParam(name = "uc") UserCave uc,
			@WebParam(name = "studentId") String stubs_id,
			@WebParam(name = "studentName") String stubs_name,
			@WebParam(name = "unGrdtSchool") int stuedu_unGrdtSchool,
			@WebParam(name = "unGrdtMajor") String stuedu_unGrdtMajor,
			@WebParam(name = "majorId") int stubs_majorID,
			@WebParam(name = "learnForm") int stuext_learnMeanType,
			@WebParam(name = "index") int index) {

		String queryString = "  ";
		if (!stubs_id.isEmpty()) {
			queryString = queryString + " and bs.stubs_id=" + stubs_id;
		}
		if (!stubs_name.isEmpty()) {
			queryString = queryString + " and bs.stubs_name like '%"
					+ stubs_name + "%' ";
		}
		if (stuedu_unGrdtSchool != -1) {
			queryString = queryString + " and edu.stuedu_unGrdtSchool="
					+ stuedu_unGrdtSchool;
		}
		if (!stuedu_unGrdtMajor.equals("-1")) {
			queryString = queryString + " and edu.stuedu_unGrdtMajor like '%"
					+ stuedu_unGrdtMajor + "%' ";
		}
		if (stubs_majorID != -1) {
			queryString = queryString + " and bs.stubs_majorID="
					+ stubs_majorID;
		}
		if (stuext_learnMeanType != -1) {
			queryString = queryString + " and ext.stuext_learnMeanType='"
					+ stuext_learnMeanType + "' ";
		}

		queryString = " StudentBaseInfo bs ,StudentEduBkInfo edu,StudentExtendInfo ext "
				+ " where bs.stubs_id=edu.stuedu_id and bs.stubs_id=ext.stuext_id "
				+ queryString;

		return getStudentInfoList(queryString, index, StudentBaseInfo.class,
				"bs");
	}

	/**
	 * 修改学生信息
	 * 
	 * @param bsBean
	 *            学生基本信息
	 * @param apBean
	 *            学生申请信息
	 * @param eduBean
	 *            学生教育背景
	 * @param extBean
	 *            学生附加信息
	 * @return
	 */
	public String ModifyStudentInfo(
			@WebParam(name = "baseEntry") StudentBaseInfo bsBean,
			@WebParam(name = "applyEntry") StudentApplyInfo apBean,
			@WebParam(name = "eduEntry") StudentEduBkInfo eduBean,
			@WebParam(name = "extEntry") StudentExtendInfo extBean) {

		BigDecimal studentID=bsBean.getStubs_id();
		apBean.setStuapl_id(studentID);
		eduBean.setStuedu_id(studentID);
		extBean.setStuext_id(studentID);
		
		PersistenceHelper.modifyPartialEntity(AllInfoUpdateAccess.class,
				bsBean, apBean, eduBean, extBean);
		return "修改学生信息成功";
	}

	/**
	 * 添加学生信息
	 * 
	 * @param bsBean
	 *            学生基本信息
	 * @param apBean
	 *            学生申请信息
	 * @param eduBean
	 *            学生教育背景
	 * @param extBean
	 *            学生附加信息
	 * @return
	 * @throws NumberFormatException
	 * @throws Exception
	 */
	public String NewStudentInfo(
			@WebParam(name = "baseEntry") StudentBaseInfo bsBean,
			@WebParam(name = "applyEntry") StudentApplyInfo apBean,
			@WebParam(name = "eduEntry") StudentEduBkInfo eduBean,
			@WebParam(name = "extEntry") StudentExtendInfo extBean)
			throws NumberFormatException, Exception {

		java.math.BigDecimal id = new java.math.BigDecimal(
				newID(extBean.getStuext_examPlace()));

		bsBean.setStubs_diploma(1);
		bsBean.setStubs_number("");
		bsBean.setStubs_id(id);
		apBean.setStuapl_id(id);
		eduBean.setStuedu_id(id);
		extBean.setStuext_id(id);

		extBean.fillInNcsyField();

		PersistenceHelper.addEntity(bsBean, apBean, eduBean, extBean);

		return "添加学生信息成功,报名号：" + id;
	}

	/**
	 * 生成新的学生编号
	 * 
	 * @param place
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	String newID(String place) throws Exception {
		ConfigService cfgSer = new ConfigService();
		ConfigInfo cfgInfo = cfgSer.readConfig();
		String s1 = Integer.valueOf(
				Integer.valueOf(cfgInfo.getYear()).intValue() % 100).toString();// 年份

		String s2 = "33";// 省份
		String s3 = cfgInfo.getSeason();// 季节
		if (s3.equals("0"))
			s3 = "01";
		else if (s3.equals("1"))
			s3 = "06";
		String s4 = "0" + place;// 考试地点
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("zjusc");
		EntityManager em = emf.createEntityManager();
		Query query = em
				.createQuery("select count(*)   from StudentBaseInfo bs");

		List li = query.getResultList();
		Long i = (Long) li.get(0) + 1;

		String s5 = String.format("%04d", i + 1); // 自编号
		return s1 + s2 + s3 + s4 + s5;
	}

	/**
	 * 修改学生基本信息
	 * 
	 * @param biBean
	 * @return
	 */
	public String ModifyStudentBaseInfo(
			@WebParam(name = "baseEntry") StudentBaseInfo biBean) {

		updateEntities(biBean);

		return "修改考生基本信息成功";
	}

	/**
	 * 修改学生受教育信息
	 * 
	 * @param ebiBean
	 * @return
	 */
	public String ModifyStudentEduBkInfo(
			@WebParam(name = "eduEntry") StudentEduBkInfo ebiBean) {

		updateEntities(ebiBean);

		return "修改考生教育背景信息成功";
	}

	/**
	 * 修改学生的报考信息
	 * 
	 * @param aiBean
	 * @return
	 */
	public String ModifyStudentApplyInfo(
			@WebParam(name = "applyEntry") StudentApplyInfo aiBean) {

		updateEntities(aiBean);

		return "修改考生报考信息成功";
	}

	/**
	 * 修改学生的扩展信息
	 * 
	 * @param eiBean
	 * @return
	 */
	public String ModifyStudentExtendInfo(
			@WebParam(name = "extEntry") StudentExtendInfo eiBean) {

		updateEntities(eiBean);

		return "修改考生信息成功";
	}

	/**
	 * 修改 各种实体信息
	 * 
	 * @param infoBeans
	 */
	void updateEntities(Object... infoBeans) {
		PersistenceHelper.modifyEntity(infoBeans);
	}

}
